﻿namespace Jhong.FunMVCBlog.Admin.Controllers
{
    using Jhong.FunMVC;
    using Jhong.FunMVCBlog.Core.Data;
    using Jhong.FunMVCBlog.Core.Entity;
    using Jhong.FunMVCBlog.Core.Infrastructure;
    using System;
    using System.IO;

    public class AttachmentController : SecurityController
    {
        public ActionResult List()
        {
            return View();
        }

        private AttachmentData _attachmentData = new AttachmentData();

        public ActionResult GetData(int pageIndex, int itemsPerPage)
        {
            var data = this._attachmentData.GetList(pageIndex, itemsPerPage);
            var page = data.GetPageHelper();
            return AjaxResult(true, data: new { Items = data.Items, Page = page.GetPageHtml() });
        }

        public ActionResult Delete(Guid id)
        {
            var entity = this._attachmentData.GetByID(id);
            File.Delete(Path.Combine(WebSiteRootPath, entity.SavePath.TrimStart('/')));
            this._attachmentData.Delete(entity);
            return AjaxResult(true, "删除成功");
        }

        public ActionResult UploadAttachment()
        {
            var file = Request.Forms.Files[0];
            var savePath = string.Format("/Static/Files/{0}/{1}", DateTime.Now.Year.ToString(), DateTime.Now.Month.ToString());
            var rSavePath = Path.Combine(WebSiteRootPath, savePath.TrimStart('/'));
            if (false == Directory.Exists(rSavePath)) Directory.CreateDirectory(rSavePath);
            var fileName = "/" + Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
            savePath += fileName;
            rSavePath += fileName;

            file.SaveAs(rSavePath);
            var fileinfo = new FileInfo(rSavePath);
            var md5 = rSavePath.GetMD5HashFromFile();
            var model = new Attachment()
            {
                SavePath = savePath,
                ID = Guid.NewGuid(),
                CreateTime = DateTime.Now,
                FileName = Path.GetFileName(file.FileName),
                FileSize = fileinfo.Length,
                MD5 = md5
            };
            this._attachmentData.Insert(model);
            return AjaxResult(true, "上传成功");
        }
    }
}